package com.cheyun.netsalev3.tencenttim.profile;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.tencenttim.BaseActivity;
import com.cheyun.netsalev3.tencenttim.utils.Constants;
import com.cheyun.netsalev3.tencenttim.utils.DemoLog;
import com.cheyun.netsalev3.utils.PhotoUtils;
import com.cheyun.netsalev3.utils.UriUtils;
import com.cheyun.netsalev3.widget.CircleImageView;
import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.listener.DialogUIItemListener;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMFriendAllowType;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.qcloud.tim.uikit.component.LineControllerView;
import com.tencent.qcloud.tim.uikit.component.SelectionActivity;
import com.tencent.qcloud.tim.uikit.component.picture.imageEngine.impl.GlideEngine;
import com.tencent.qcloud.tim.uikit.utils.TUIKitConstants;
import com.tencent.qcloud.tim.uikit.utils.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

public class MyInfoActivity extends BaseActivity implements View.OnClickListener {
    private CircleImageView mUserIcon;

    private LineControllerView mModifyNickNameView;
    private LineControllerView mtel;
    private LinearLayout ly_face;
    private ArrayList<String> mJoinTypeTextList = new ArrayList<>();
    private ArrayList<String> mJoinTypeIdList = new ArrayList<>();
    private int mJoinTypeIndex = 2;
    private String mIconUrl;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");

    private Uri photoUri;
    private String picPath;

    private static final String TAG = MyInfoActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_profile_activity);
        init();
    }

    private void init(){
        mUserIcon = findViewById(R.id.self_icon);
        TIMUserProfile profile = TIMFriendshipManager.getInstance().querySelfProfile();
        if (profile != null) {
            if (!TextUtils.isEmpty(profile.getFaceUrl())) {
                GlideEngine.loadImage(mUserIcon, Uri.parse(profile.getFaceUrl()));
            }
        } else {
            SharedPreferences shareInfo = this.getSharedPreferences(Constants.USERINFO, Context.MODE_PRIVATE);
            String url = shareInfo.getString(Constants.ICON_URL, "");
            if (!TextUtils.isEmpty(url)) {
                GlideEngine.loadImage(mUserIcon, Uri.parse(url));
            }
        }

        ly_face = findViewById(R.id.ly_face);
        ly_face.setOnClickListener(this);
        mModifyNickNameView = findViewById(R.id.modify_nick_name);
        mModifyNickNameView.setCanNav(false);

        mtel = findViewById(R.id.tel);
        mtel.setCanNav(false);
        mJoinTypeTextList.add(getResources().getString(R.string.allow_type_allow_any));
        mJoinTypeTextList.add(getResources().getString(R.string.allow_type_deny_any));
        mJoinTypeTextList.add(getResources().getString(R.string.allow_type_need_confirm));
        mJoinTypeIdList.add(TIMFriendAllowType.TIM_FRIEND_ALLOW_ANY);
        mJoinTypeIdList.add(TIMFriendAllowType.TIM_FRIEND_DENY_ANY);
        mJoinTypeIdList.add(TIMFriendAllowType.TIM_FRIEND_NEED_CONFIRM);

        TIMFriendshipManager.getInstance().getSelfProfile(new TIMValueCallBack<TIMUserProfile>() {
            @Override
            public void onError(int i, String s) {
                DemoLog.e(TAG, "initSelfProfile err code = " + i + ", desc = " + s);
                ToastUtil.toastShortMessage("Error code = " + i + ", desc = " + s);
            }

            @Override
            public void onSuccess(TIMUserProfile profile) {
                DemoLog.i(TAG, "initSelfProfile success, timUserProfile = " + profile.toString());
                mModifyNickNameView.setContent(profile.getNickName());
                mtel.setContent(profile.getIdentifier());
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.modify_nick_name) {
            Bundle bundle = new Bundle();
            bundle.putString(TUIKitConstants.Selection.TITLE, getResources().getString(R.string.modify_nick_name));
            bundle.putString(TUIKitConstants.Selection.INIT_CONTENT, mModifyNickNameView.getContent());
            bundle.putInt(TUIKitConstants.Selection.LIMIT, 20);
            SelectionActivity.startTextSelection(this, bundle, new SelectionActivity.OnResultReturnListener() {
                @Override
                public void onReturn(Object text) {
                    mModifyNickNameView.setContent(text.toString());
                    updateProfile();
                }
            });
        }else if(v.getId() == R.id.ly_face){
            List<String> strings = new ArrayList<>();
            strings.add("拍摄" );
            strings.add("从手机相册选择");
            DialogUIUtils.showBottomSheetAndCancel(this, strings, "取消", new DialogUIItemListener() {
                @Override
                public void onItemClick(CharSequence text, int position) {
                    if(position == 0){
                        takePhoto();
                    }else {
                        pickPhoto();
                    }
                    System.out.println(text);
                    System.out.println(position);
                }
            }).show();
        }
    }

    private void updateProfile() {
        HashMap<String, Object> hashMap = new HashMap<>();

        // 头像
        if (!TextUtils.isEmpty(mIconUrl)) {
            hashMap.put(TIMUserProfile.TIM_PROFILE_TYPE_KEY_FACEURL, mIconUrl);
        }

        // 昵称
        String nickName = mModifyNickNameView.getContent();
        hashMap.put(TIMUserProfile.TIM_PROFILE_TYPE_KEY_NICK, nickName);

        // 个性签名
//        String signature = mModifySignatureView.getContent();
//        hashMap.put(TIMUserProfile.TIM_PROFILE_TYPE_KEY_SELFSIGNATURE, signature);

        // 地区
        hashMap.put(TIMUserProfile.TIM_PROFILE_TYPE_KEY_LOCATION, "sz");

        // 加我验证方式
        String allowType = mJoinTypeIdList.get(mJoinTypeIndex);
        hashMap.put(TIMUserProfile.TIM_PROFILE_TYPE_KEY_ALLOWTYPE, allowType);

        TIMFriendshipManager.getInstance().modifySelfProfile(hashMap, new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
                DemoLog.e(TAG, "modifySelfProfile err code = " + i + ", desc = " + s);
                ToastUtil.toastShortMessage("Error code = " + i + ", desc = " + s);
            }

            @Override
            public void onSuccess() {
                DemoLog.i(TAG, "modifySelfProfile success");
            }
        });
    }

    private void doPhoto(int requestCode,Intent data){
        if(requestCode == 2 )
        {
            if(data == null){
                ToastUtil.toastLongMessage("选择图片文件出错！");
                return;
            }
            photoUri = data.getData();
            if(photoUri == null ) {
                ToastUtil.toastLongMessage("选择图片文件出错！");
                return;
            }
            picPath = UriUtils.getPath(MyInfoActivity.this, photoUri);
        }else if(requestCode == 1){
            picPath = fileUri.getPath().toString();
        }
        if(picPath != null && ( picPath.endsWith(".png") || picPath.endsWith(".PNG") ||picPath.endsWith(".jpg") ||picPath.endsWith(".JPG") )){
            Intent intent = new Intent(MyInfoActivity.this, ClipImageActivity.class);
            intent.putExtra("path", picPath);
            intent.putExtra("name", System.currentTimeMillis()/1000+"_touxiang");
            intent.putExtra("type", "2");
            startActivityForResult(intent, 1);

        }else{
            ToastUtil.toastLongMessage("选择图片文件不正确！");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0:{
//                showDiaglog();
                break;
            }
            case 1: {//调用系统相机申请拍照权限回调
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (hasSdcard()) {
                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
                            photoUri= Uri.fromFile(fileUri);
                        } else {
                            photoUri = FileProvider.getUriForFile(MyInfoActivity.this, this.getPackageName()+".provider", fileUri);
                        }
                        PhotoUtils.takePicture(this, photoUri, 1);
                    } else {
                        ToastUtil.toastLongMessage("设备没有SD卡！");
                    }
                } else {

                }
                break;
            }
            case 2://调用系统相册申请Sdcard权限回调
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PhotoUtils.openPic(this, 2);
                } else {
                    ToastUtil.toastLongMessage("请允许操作SDCard！！");
                }
                break;
        }
    }


    private void takePhoto() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
//                ("您已经拒绝过一次");
                ToastUtil.toastLongMessage("您已经拒绝过一次");
            }
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        } else {//有权限直接调用系统相机拍照
            if (hasSdcard()) {
//                photoUri = Uri.fromFile(fileUri);
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
                    photoUri= Uri.fromFile(fileUri);
                } else {
                    photoUri = FileProvider.getUriForFile(MyInfoActivity.this, this.getPackageName()+".provider", fileUri);
                }
                PhotoUtils.takePicture(this, photoUri, 1);
            } else {
                ToastUtil.toastLongMessage("设备没有SD卡");
            }
        }
    }

    public void pickPhoto() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, 2);
    }
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if(resultCode == Activity.RESULT_OK){
            doPhoto(requestCode,data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
        SharedPreferences shareInfo = this.getSharedPreferences(Constants.USERINFO, Context.MODE_PRIVATE);
        String url = shareInfo.getString(Constants.ICON_URL, "");
        if (!TextUtils.isEmpty(url)) {
            GlideEngine.loadImage(mUserIcon, Uri.parse(url));
        }
    }
}
